package cn.orangeframe.neon.application.mapper;

import cn.orangeframe.neon.application.exception.TerminateWorkflowException;
import cn.orangeframe.neon.domain.entity.WorkflowTask;
import cn.orangeframe.neon.domain.enums.TaskStatus;
import cn.orangeframe.neon.domain.enums.TaskType;
import cn.orangeframe.neon.domain.model.TaskModel;
import cn.orangeframe.neon.domain.model.WorkflowModel;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Component(TaskType.TASK_TYPE_FORK)
public class ForkTaskMapper implements TaskMapper {

    @Override
    public String getTaskType() {
        return TaskType.TASK_TYPE_FORK;
    }

    @Override
    public List<TaskModel> getMappedTasks(TaskMapperContext taskMapperContext) throws TerminateWorkflowException {

        WorkflowTask workflowTask = taskMapperContext.getTaskToSchedule();
        WorkflowModel workflowModel = taskMapperContext.getWorkflowInstance();
        Map<String, Object> taskInput = taskMapperContext.getTaskInput();
        int retryCount = taskMapperContext.getRetryCount();

        List<TaskModel> tasksToBeScheduled = new LinkedList<>();
        TaskModel forkTask = taskMapperContext.createTaskModel();
        forkTask.setTaskType(TaskType.TASK_TYPE_FORK);
        forkTask.setTaskDefName(TaskType.TASK_TYPE_FORK);
        forkTask.setStartTime(System.currentTimeMillis());
        forkTask.setStatus(TaskStatus.COMPLETED);
        forkTask.setInputData(taskInput);
        tasksToBeScheduled.add(forkTask);

        List<List<WorkflowTask>> forkTasks = workflowTask.getForkTasks();
        for (List<WorkflowTask> wfts : forkTasks) {
            WorkflowTask wft = wfts.getFirst();
            List<TaskModel> tasks =
                    taskMapperContext
                            .getDeciderService()
                            .getTasksToBeScheduled(workflowModel, wft, retryCount);
            tasksToBeScheduled.addAll(tasks);
        }

        WorkflowTask joinWorkflowTask = workflowModel
                .getWorkflowDefinition()
                .getNextTask(workflowTask.getTaskReferenceName());
        if (joinWorkflowTask == null || !joinWorkflowTask.getType().equals(TaskType.JOIN.name())) {
            throw new TerminateWorkflowException(
                    "Fork task definition is not followed by a join task.  Check the blueprint");
        }
        List<TaskModel> joinTask =
                taskMapperContext
                        .getDeciderService()
                        .getTasksToBeScheduled(workflowModel, joinWorkflowTask, retryCount);

        tasksToBeScheduled.addAll(joinTask);
        return tasksToBeScheduled;
    }
}
